import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { Badge, Card, message, Pagination, Table } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import Ellipsis from '@/components/Ellipsis';
import * as G from '@/utils/common';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import PropTypes from 'prop-types';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
// import DetailModal from "./detailModal"
import { routerRedux } from 'react-router-dom';

const mapStateToProps = (state: any) => ({
  remoteController: state.remoteController,
  loading: state.loading.models['remoteController'],
});

class RemoteControlLogQuery extends PureComponent<any, any> {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      detailVisible: false,
      // detailData: {},
      // colorData: {},
      extendStatus: false,
      formValues: {
        startTime: moment()
          .add(-1, 'week')
          .valueOf(),
        endTime: moment().valueOf(),
      },
      pagination: {
        pageNo: 1,
        pageSize: 10,
      },
    };
  }
  
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;

    this.unlisten = this.props.history.listen((location: any, action: any) => {
      const { sourcePage } = location
      let values = {
        ...pagination
      }
      if ( sourcePage === 'remoteControllerLogQueryDetail' ) {
        //  详情返回
        const tempValues = sessionStorage.getItem('remoteControllerLogQuerySearchValues')
        values = {
          ...values,
          ...(JSON.parse(tempValues) || {})
        }
        this.setState({
          extendStatus: true,
        })
      }

      const { pageNo, pageSize, ...rest } = values;
      this.setState({
        formValues: {
          ...formValues,
          ...rest,
        },
        pagination: {
          pageNo,
          pageSize
        }
      }, () => {
        const { formValues, pagination } = this.state
        this.searchForm.current.setFieldsValue({
          ...formValues,
          startTime: moment(formValues.startTime),
          endTime: moment(formValues.endTime),
        });
        dispatch({
          type: 'remoteController/getFetchPage',
          payload: { url: '/connectLog/vhlCtlLogList', ...formValues, ...pagination },
        });
      })

    })
  }

  componentWillUnmount() {
    if(this.unlisten) {
      this.unlisten();
    }
  }

  /**
   * 参数校验
   * @param fieldsValue
   */
  dataFormat = (fields: any) => {
    const { pagination } = this.state;
    if (G.isNotEmptyAndNil(fields['startTime']) && G.isNotEmptyAndNil(fields['endTime'])) {
      fields['startTime'] = moment(fields.startTime).valueOf();
      fields['endTime'] = moment(fields.endTime).valueOf();
      return {...fields,...pagination};
    } else {
      message.warning('请填写起止时间！');
      return false;
    }
  };

  handleFormReset = (fields: any) => {
    let startTime = moment()
      .add(-1, 'week')
      .valueOf();
    let endTime = moment().valueOf();
    this.searchForm.current.setFieldsValue({
      startTime: moment(startTime),
      endTime: moment(endTime),
    });
    this.setState({
      formValues: {
        startTime: startTime,
        endTime: endTime,
      },
      pagination: {
        pageNo: 1,
        pageSize: 10,
      },
    });
  };

  handleTableChange = (pagination: any, filters: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    const params = {
        ...formValues,
        pageNo: current,
        pageSize: pageSize,
      ...filters,
    };
    this.setState({
      pagination: {
        pageNo: current,
        pageSize: pageSize
      }
    }, () => {
      dispatch({
        type: 'remoteController/getFetchPage',
        payload: { url: '/connectLog/vhlCtlLogList', ...params },
      });
    })
  };

  // // 查看详情
  // viewDetail = (key:any) =>{
  //   console.log(key);
  //   const { dispatch } = this.props;
  //   const param = {
  //     id: key
  //   };
  //   dispatch({
  //     type: 'remoteController/getFetchPage',
  //     payload: { url: '/connectLog/vhlCtlLogDetail', ...param},
  //     callback: (res:any) => {
  //       console.log(res);
  //       this.setState({ detailData: res.data, });
  //       const data = res.data;
  //       // 判断各节点颜色
  //       let obj1 : {color1: string};
  //       let obj2 : {color2: string};
  //       let obj3 : {color3: string};
  //       let obj4 : {color4: string};
  //       let obj5 : {color5: string};
  //       let obj6 : {color6: string};
  //       let obj7 : {color7: string};
  //       if(data.requestTime == ''){
  //         console.log('1')
  //         obj1 = {color1: "gray"}
  //       }else{
  //         obj1 = {color1: "green"}

  //       }
  //       if(data.smsTime == '' ){
  //         console.log('2')
  //         obj2 = {color2: "gray"}
  //       }else{
  //         obj2 = {color2: "green"}

  //       }
  //       if((!data.dcvpRequest) || JSON.stringify(data.dcvpRequest) == '{}' || data.dcvpRequest.dcvpRequestTime == ''){
  //         console.log('3')
  //         obj3 = {color3: "gray"}
  //       }else{
  //         obj3 = {color3: "green"}

  //       }
  //       if((!data.tboxAck) || JSON.stringify(data.tboxAck) == '{}' || data.tboxAck.tboxAckTime == ''){
  //         console.log('4')
  //         obj4 = {color4: "gray"}
  //       }else{
  //         obj4 = {color4: "green"}

  //       }
  //       if((!data.dcvpAck) || JSON.stringify(data.dcvpAck) == '{}' || data.dcvpAck.dcvpAckTime == ''){
  //         console.log('5')
  //         obj5 = {color5: "gray"}
  //       }else{
  //         obj5 = {color5: "green"}

  //       }
  //       if((!data.tboxResult) || JSON.stringify(data.tboxResult) == '{}' || data.tboxResult.tboxResultTime == ''){
  //         console.log('6')
  //         obj6 = {color6: "gray"}
  //       }else{
  //         obj6 = {color6: "green"}

  //       }
  //       if((!data.dcvpResult) || JSON.stringify(data.dcvpResult) == '{}' || data.dcvpResult.dcvpResultTime == ''){
  //         console.log('7')
  //         obj7 = {color7: "gray"}
  //       }else{
  //         obj7 = {color7: "green"}

  //       }

  //       this.setState({
  //         colorData : {...obj1,...obj2,...obj3,...obj4,...obj5,...obj6,...obj7}
  //       })
  //     },
  //   }).then( ()=>{
  //   //   console.log('data--', data);
  //   //   this.setState({
  //   //     detailVisible: true
  //   // });
  //   const { dispatch } = this.props;
  //   const path = {
  //     pathname: '/connectPlat/remoteControllerLogQuery/remoteControllerLogQueryDetail',
  //   };
  //   dispatch(routerRedux.push(path));
  //   });
  // }

  handleDetail = (id: any) => {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;
    const searchValues = {
      ...formValues,
      ...pagination
    }
    sessionStorage.setItem('remoteControllerLogQuerySearchValues', JSON.stringify(searchValues));
    dispatch({
      type: 'remoteController/getFetchPage',
      payload: { url: '/connectLog/vhlCtlLogDetail', id },
      callback: (res: any) => {
        const dcvpRequest = JSON.parse(res.data.dcvpRequest);
        const tboxAck = JSON.parse(res.data.tboxAck);
        const dcvpAck = JSON.parse(res.data.dcvpAck);
        const tboxResult = JSON.parse(res.data.tboxResult);
        const dcvpResult = JSON.parse(res.data.dcvpResult);
        const data = res.data;
        // 判断各节点颜色
        let obj1: { color1: string };
        let obj2: { color2: string };
        let obj3: { color3: string };
        let obj4: { color4: string };
        let obj5: { color5: string };
        let obj6: { color6: string };
        let obj7: { color7: string };
        if (data.requestTime == '') {
          console.log('1');
          obj1 = { color1: 'gray' };
        } else {
          obj1 = { color1: 'green' };
        }
        if (data.smsTime == '') {
          console.log('2');
          obj2 = { color2: 'gray' };
        } else {
          obj2 = { color2: 'green' };
        }
        if (!dcvpRequest || JSON.stringify(dcvpRequest) == '{}') {
          console.log('3');
          obj3 = { color3: 'gray' };
        } else {
          obj3 = { color3: 'green' };
        }
        if (!tboxAck || JSON.stringify(tboxAck) == '{}') {
          console.log('4');
          obj4 = { color4: 'gray' };
        } else {
          obj4 = { color4: 'green' };
        }
        if (!dcvpAck || JSON.stringify(dcvpAck) == '{}') {
          console.log('5');
          obj5 = { color5: 'gray' };
        } else {
          obj5 = { color5: 'green' };
        }
        if (!tboxResult || JSON.stringify(tboxResult) == '{}') {
          console.log('6');
          obj6 = { color6: 'gray' };
        } else {
          obj6 = { color6: 'green' };
        }
        if (!dcvpResult || JSON.stringify(dcvpResult) == '{}') {
          console.log('7');
          obj7 = { color7: 'gray' };
        } else {
          obj7 = { color7: 'green' };
        }
        const colorData = { ...obj1, ...obj2, ...obj3, ...obj4, ...obj5, ...obj6, ...obj7 };
        sessionStorage.setItem('colorData', JSON.stringify(colorData));
        sessionStorage.setItem('detailData', JSON.stringify(res.data));
        const path = {
          pathname: '/connectPlat/remoteControllerLogQuery/remoteControllerLogQueryDetail',
        };
        dispatch(routerRedux.push(path));
      },
    });

    // const path = {
    //   pathname: '/connectPlat/remoteControllerLogQuery/remoteControllerLogQueryDetail',
    // };
    // dispatch(routerRedux.push(path));
  };

  getData() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'remoteController/getFetchPage',
      payload: { url: '/connectLog/vhlCtlLogList', ...formValues },
    });
  }
  close = () => {
    this.setState({
      detailVisible: false,
      detailData: {},
    });
    this.getData;
  };
  render() {
    const {
      remoteController: {
        pageData: { list, pageCount, pageNo, pageSize, itemSize },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const pagination = { current: pageNo, pageSize: pageSize, total: itemSize };
    const { detailVisible, formValues, extendStatus } = this.state;
    const columns = [
      {
        title: 'VIN码',
        dataIndex: 'vin',
        // render: (text: any) => {
        //   return (
        //     <Ellipsis length={10} tooltip>
        //       {text}
        //     </Ellipsis>
        //   );
        // },
      },
      {
        title: '控制类型',
        dataIndex: 'ctlType',
        render: text => {
          if (text == null) {
            return '';
          }
          return getDicByKey(this.context.dicData, `ctlType`, text + '');
          // <Ellipsis length={10} tooltip>
          //   {getDicByKey(this.context.dicData, `ctlType`, text + '')}
          // </Ellipsis>
        },
      },
      {
        title: '远控状态',
        dataIndex: 'ctlStatus',
        ellipsis: true,
        render: text => {
          if (text == null) {
            return '';
          }
          return getDicByKey(this.context.dicData, `ctlStatus`, text + '');
        },
      },
      {
        title: '请求时间',
        dataIndex: 'requestTime',
        ellipsis: true,
        // width: 150,
      },
      {
        title: 'ACK时间',
        dataIndex: 'ackTime',
        ellipsis: true,
        // width: 150,
      },
      {
        title: 'ACK状态',
        dataIndex: 'ackStatus',
        ellipsis: true,
        render: text => {
          if (text == null) {
            return '';
          } else if (text === 0) {
            return '成功';
          } else if (text === 1) {
            return '失败';
          } else {
            return '';
          }
        },
        // width: 150,
      },
      {
        title: '结果返回时间',
        dataIndex: 'resultTime',
        ellipsis: true,
        // width: 150,
      },
      // {
      //   title: '结果错误码',
      //   dataIndex: 'resultCode',
      //   // render: (text: any) => {
      //   //   return (
      //   //     <Ellipsis length={10} tooltip>
      //   //       {text}
      //   //     </Ellipsis>
      //   //   );
      //   // },
      // },
      // {
      //   title: '错误描述',
      //   dataIndex: 'errorMessage',
      //   // render: (text: any) => {
      //   //   return (
      //   //     <Ellipsis length={10} tooltip>
      //   //       {text}
      //   //     </Ellipsis>
      //   //   );
      //   // },
      // },
      {
        title: '唯一流水号',
        dataIndex: 'serialNum',
        // ellipsis: true,
        // render: (text:any) => {
        //   return (
        //     <Ellipsis length={10} tooltip>
        //       {text}
        //     </Ellipsis>
        //   );
        // },
      },
      {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'remoteControllerLogQuery_show',
              onConfirm: () => this.handleDetail.bind(this)(record.id),
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      // ...itemSize,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const ctlType = getDictOptionsByCode(this.context.dicData, 'ctlType');
    const ctlStatus = getDictOptionsByCode(this.context.dicData, 'ctlStatus');

    let searchItems = [
      {
        title: '请求时间起',
        type: 'datePicker',
        key: 'startTime',
        format: 'YYYY-MM-DD HH:mm:ss',
        showTime: true,
        showToday: true,
        initialValue: moment(this.state.formValues.startTime),
        rules: [{ required: true, message: '请求时间起必选!' }],
      },
      {
        title: '请求时间止',
        type: 'datePicker',
        key: 'endTime',
        format: 'YYYY-MM-DD HH:mm:ss',
        showTime: true,
        showToday: true,
        initialValue: moment(this.state.formValues.endTime),
        rules: [{ required: true, message: '请求时间止必选!' }],
      },
      {
        title: 'VIN码',
        type: 'input',
        // maxLength: 18,
        key: 'vin',
        rules: [
          {
            required: false,
            message: '请输入10-17的英文和数字',
            min: 10,
            max: 17,
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
      },
      {
        title: '控制类型',
        type: 'select',
        selectOptions: ctlType,
        key: 'ctlType',
      },
      {
        title: '远控状态',
        type: 'select',
        selectOptions: ctlStatus,
        key: 'ctlStatus',
      },
      {
        title: '唯一流水号',
        type: 'input',
        maxLength: 18,
        key: 'serialNum',
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            isExtend={extendStatus}
            fetchParams={{
              type: 'remoteController/getFetchPage',
              url: '/connectLog/vhlCtlLogList',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card style={{ marginTop: 12 }} bordered={false}>
          <Table
            size={'small'}
            rowKey={record => record.id}
            dataSource={list ? list : ''}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'max-content' }}
          />
        </Card>
        {/* <DetailModal 
          modalVisible={detailVisible}
          closeModal={this.close}
          // closeModal={()=>this.setState({detailVisible:false, detailData: {}})}
          detailData={this.state.detailData}
          colorData={this.state.colorData}
        /> */}
      </div>
    );
  }
}

export default connect(mapStateToProps)(RemoteControlLogQuery);
